package lt.marsrutai.mobile.android.util;

import lt.marsrutai.mobile.android.manager.AppPreferenceManager;
import lt.marsrutai.mobile.android.manager.PreferenceDefaultValueResolvers;
import android.content.Context;
import android.preference.PreferenceManager;

/**
 * Utility class for preference value retrieval
 *
 * @author Justas
 *
 */
public class PreferenceUtils {

    public static final String SCHEDULE_ACTIVITY_OPENED = "schedule_activity_opened";
    public static final String MAP_VIEW_TYPE_SATELLITE = "map_view_type_satellite";
    public static final String SELECTED_SCOPE_FOLDER = "selected_scope_folder";

    /**
     * <p>Resolves the preference with the provided key and casts it to the expected type.</p>
     * <p>If the preference is saved, it's value is fetched, otherwise a default value is returned</p>
     *
     * @param context Context
     * @param key Preference key
     * @return Current preference value if set, otherwise it's default value.
     * @see AppPreferenceManager#resolveDefaultValue(Context, String)
     */
    @SuppressWarnings("unchecked")
    public static <T> T getPreferenceValue(Context context, String key) {
        Object value = PreferenceManager.getDefaultSharedPreferences(context).getAll().get(key);

        // If none is currently set, resolve it's default
        return value == null ? PreferenceDefaultValueResolvers.<T>resolveDefaultValue(context, key) : (T) value;
    }

    /**
     * <p>Sets Boolean preference value.</p>
     *
     * @param context Context
     * @param key Preference key
     * @param value Preference value
     */
    public static void setBooleanPreferenceValue(Context context, String key, Boolean value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value).commit();
    }

    /**
     * <p>Sets String preference value.</p>
     *
     * @param context Context
     * @param key Preference key
     * @param value Preference value
     */
    public static void setStringPreferenceValue(Context context, String key, String value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
    }
}
